<?php

namespace app\common\model;

use think\Model;


class Uselog extends Model
{

    

    

    // 表名
    protected $name = 'uselog';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'status_text'
    ];



    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2'), '3' => __('Type 3')];
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    /**
     * 领用添加
     * @return void
     */
    public static function addLog($stand_id,$user_id,$cgproduct_id,$type,$num=0)
    {
        Db::startTrans();
        try {
            $insert = [
                'stand_id' => $stand_id,
                'user_id' => $user_id,
                'cgproduct_id' => $cgproduct_id,
                'type' => $type,
                'num' => $num,
                'createtime' => time()
            ];
            $res = self::create($insert);
            if(!$res){
                throw new \Exception('领用单添加失败');
            }
            $cgproduct = Cgproduct::get($cgproduct_id);
            $cgproduct->all_num = $cgproduct->all_num - $num;
            $cgproduct->save();
            Db::commit();
            return true;
        }catch (\Exception $e){
            Db::rollback();
            return false;
        }
    }


    public function admin()
    {
        return $this->belongsTo('Admin', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function cgproduct()
    {
        return $this->belongsTo('Cgproduct', 'cgproduct_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function stand()
    {
        return $this->belongsTo('Stand', 'stand_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
